<?php

namespace apiend\modules\inventory\models;

use Yii;
use common\helpers\ArrayHelper;
use common\models\inventory\InventoryLog;
use common\models\inventory\InventoryBill;

/**
 * 判断批次查询结果
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class InventoryResultLogic extends \apiend\models\searchs\DashboardSearch {

    /**
     * @var array 盘点批次
     */
    private $_batch = null;

    /**
     * @var array 正常数 
     */
    public $result = [];

    /**
     * @var string 异常提醒
     */
    public $abnormals = '';

    /**
     * @var array 票据结果
     */
    public $bills = [];

    /**
     * @var array 多余票据
     */
    private $_surplus = [];

    /**
     * @var array 缺失票据
     */
    private $_loss = [];

    /**
     * @var array 正常票据
     */
    private $_normal = [];

    /**
     * @inheritdoc
     */
    public function setBatch($batch = null) {
        $this->_batch = $batch;
    }

    /**
     * @inheritdoc
     */
    protected function setResult() {
        $this->_surplus = $this->getSurplus();
        $this->_loss = $this->getLoss();
        $this->_normal = $this->getNormals();

        $errors = count($this->_surplus) + count($this->_loss);
        $normals = count($this->_normal);
        $totals = $errors + $normals;

        return [
            'scans' => $this->_batch->amount,
            'totals' => $totals,
            'normals' => $normals,
            'errors' => $errors,
        ];
    }

    /**
     * 异常的数据
     * @inheritdoc
     */
    protected function setAbnormals() {
        $cnt = InventoryLog::find()->where([
            'batch_id' => $this->_batch->id,
            'bill_id' => 0
        ])->count();
        if ($cnt) {
            return '扫描的票据中存在' . $cnt . '条异常票据';
        }
        return '';
    }

    /**
     * 异常的数据
     * @inheritdoc
     */
    protected function setBills() {
        return ArrayHelper::merge($this->_surplus, $this->_loss, $this->_normal);
    }

    /**
     * 多出的票据
     * @inheritdoc
     */
    private function getSurplus() {
        $model = new InventoryBill();
        $model->batch = $this->_batch;
        $model->type = InventoryBill::TYPE_SURPLUS;
        return $model->search();
    }

    /**
     * 缺失的票据
     * @inheritdoc
     */
    private function getLoss() {
        $model = new InventoryBill();
        $model->batch = $this->_batch;
        $model->type = InventoryBill::TYPE_LOSS;
        return $model->search();
    }

    /**
     * 正常的数据
     * @inheritdoc
     */
    private function getNormals() {
        $model = new InventoryBill();
        $model->batch = $this->_batch;
        $model->type = InventoryBill::TYPE_NORMAL;
        return $model->search();
    }

}
